package servlet;

import entity.Emp;
import util.ParameterUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 黄衡熙
 * @version 1.0
 */
@WebServlet("*.emp")
public class EmpServlet extends HttpServlet {
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        String servletPath = req.getServletPath();
        System.out.println("servletPath:" + servletPath);
        switch (servletPath) {
            case "/showAdd.emp":
                showAddEmp(req, resp);
                break;
            case "/add.emp":
                addEmp(req, resp);
                break;
            case "/findAll.emp":
                findAll(req, resp);
                break;
            case "/findById.emp":
                showModifyEmp(req, resp);
                break;
            case "/modify.emp":
                modifyEmp(req, resp);
                break;
            case "/delete.emp":
                deleteEmp(req, resp);
                break;
            default:
                out.println("<h1 style='color:red;'>对不起,您访问的资源不存在,请检查地址是否正确</h1>");
                break;
        }
    }

    public void showAddEmp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/ems/addEmp.jsp").forward(req, resp);
    }

    public void addEmp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//       后端返回数据给前端到浏览器的响应
        resp.setContentType("text/html;charset=utf-8");
//        用于正确解析前端提交的中文参数
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        String name = req.getParameter("name");
        String salary = req.getParameter("salary");
        String gender = req.getParameter("gender");
        String edu = req.getParameter("edu");
        String[] hobbies = req.getParameterValues("hobbies");
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8", "root", "qq670892");
            String sql = "insert into t_emp(name,salary,gender,edu,hobbies) values(?,?,?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, name);
            ps.setDouble(2, Double.parseDouble(salary));
            ps.setString(3, gender);
            ps.setString(4, edu);
//            此处把字符数组转化为字符串
            ps.setString(5, ParameterUtil.arrayToString(hobbies));
            ps.executeUpdate();
//            req.getRequestDispatcher("/findAll.emp").forward(req, resp);
            resp.sendRedirect(req.getContextPath()+"/findAll.emp");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("注册驱动失败");
        } catch (SQLException e) {
            throw new RuntimeException("获取连接异常");
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放资源异常");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放资源异常");
                }
            }
        }
    }

    public void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Emp> emps = new ArrayList<>();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8", "root", "qq670892");
            String sql = "select id,name,salary from t_emp";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                Emp emp = new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emps.add(emp);
            }
//            存储数据
            req.setAttribute("emps", emps);
//            转发
            req.getRequestDispatcher("/ems/empList.jsp").forward(req, resp);

        } catch (ClassNotFoundException e) {
            throw new RuntimeException("未找到驱动");
        } catch (SQLException e) {
            throw new RuntimeException("数据访问异常");
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放资源失败");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放资源失败");
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放资源失败");
                }
            }
        }
    }

    public void showModifyEmp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        String id = req.getParameter("id");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Emp> emps = new ArrayList<>();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8", "root", "qq670892");
            String sql = "select id,name,salary,gender,edu,hobbies from t_emp where id=?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, Integer.parseInt(id));
            rs = ps.executeQuery();
            if (rs.next()) {
                Emp emp = new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emp.setGender(rs.getString("gender"));
                emp.setEdu(rs.getString("edu"));
                emp.setHob(rs.getString("hobbies"));
                emps.add(emp);
            }
            //            存储数据
            req.setAttribute("emps", emps);
//            转发
            req.getRequestDispatcher("/ems/modifyEmp.jsp").forward(req, resp);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("注册驱动异常");
        } catch (SQLException e) {
            throw new RuntimeException("获取连接异常");
        }finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放资源失败");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放资源失败");
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放资源失败");
                }
            }
        }
    }

    public void modifyEmp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        String id=req.getParameter("id");
        String name = req.getParameter("name");
        String salary=req.getParameter("salary");
        String gender=req.getParameter("gender");
        String edu=req.getParameter("edu");
        String[] hobbies=req.getParameterValues("hobbies");
        Connection conn=null;
        PreparedStatement ps=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8", "root", "qq670892");
            String sql="update t_emp set name=?,salary=?,gender=?,edu=?,hobbies=? where id=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setDouble(2, Double.parseDouble(salary));
            ps.setString(3,gender);
            ps.setString(4,edu);
            ps.setString(5,ParameterUtil.arrayToString(hobbies));
            ps.setInt(6,Integer.parseInt(id));
            ps.executeUpdate();
            resp.sendRedirect(req.getContextPath()+"/findAll.emp");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("注册驱动异常");
        } catch (SQLException e) {
            throw new RuntimeException("获取连接异常");
        }finally {
            if(conn !=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放资源异常");
                }
            }if(ps !=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放资源异常");
                }
            }
        }
    }

    public void deleteEmp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        String id=req.getParameter("id");
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8","root","qq670892");
            String sql="delete from t_emp where id=?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, Integer.parseInt(id));
            ps.executeUpdate();
            req.getRequestDispatcher("findAll.emp").forward(req, resp);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("注册驱动异常");
        } catch (SQLException e) {
            throw new RuntimeException("获取连接异常");
        }finally {
            if(conn !=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放资源异常");
                }
            }if(ps !=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放资源异常");
                }
            }
        }
    }
}
